//
//  NetCenter.m
//  lcs_c
//
//  Created by chaiyanan on 15/8/4.
//  Copyright (c) 2015年 jinxin. All rights reserved.
//

#import "NetCenter.h"
#import "AFNetworking.h"
#import "Log.h"

@implementation NetCenter

+ (void)getDataFromURL:(NSString *)url params:(Param *)params parser:(Parser *)parser result:(NetParserResult)result failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    LLog(@"_____requestUrl:%@\n_____param:%@",url,[params buidlParam2Dictionary]);
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 25.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager GET:UrlJoint(Key_BaseUrl, url) parameters:[params buidlParam2Dictionary] success:^(NSURLSessionDataTask *task, id responseObject) {
        LLog(@"\n_____requestUrl:%@\n",url);
        if (result)
        {
            NSDictionary *dict = (NSDictionary *)responseObject;
            if ([dict[Key_Code] integerValue]==-1)
            {
                [self pushToLoginVC];
            }
            
            ParserResult *parserResult = [parser parseResponseDictionary:responseObject];
            result(parserResult);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        LLog(@"\n_____requestUrl:%@\n",url);
        if (failure)
        {
            failure(error);
            LLog(@"error:%@",[error description]);
        }
        
    }];
}

+ (void)postDataFromURL:(NSString *)url params:(Param *)params parser:(Parser *)parser result:(NetParserResult)result failure:(void (^)(NSError *))failure
{
    [self postDataFromURL:url params:params parser:parser result:result failure:failure progressBlock:nil];
}

+ (void)postDataFromURL:(NSString *)url params:(Param *)params parser:(Parser *)parser result:(NetParserResult)result failure:(void (^)(NSError *))failure progressBlock:(void (^)(float))progress
{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    [mgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    mgr.requestSerializer.timeoutInterval = 25.f;
    if (progress)
    {
        mgr.requestSerializer.timeoutInterval = 40.f;
    }
    [mgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    NSDictionary *param = [params buidlParam2Dictionary];
    NSDictionary *imageParam = [params buidImageParam2Dictionary];
    
    // 2.发送POST请求
    
    LLog(@"_____requestUrl:%@\n_____param:%@",UrlJoint(Key_BaseUrl, url),[params buidlParam2Dictionary]);
    
    LLog(@"%lu",(unsigned long)imageParam.allKeys.count);
    if (imageParam.allKeys.count>0)
    {
        AFHTTPRequestOperation* operation = [mgr POST:UrlJoint(Key_BaseUrl, url) parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                             {
                                                 for (NSString* imageKey in imageParam.allKeys)
                                                 {
                                                     NSData* imageData=[imageParam objectForKey:imageKey];
                                                     if ([imageData length]>0)
                                                     {
                                                         if ([[param allKeys]containsObject:@"fileType"])
                                                         {
                                                             if ([param[@"fileType"] intValue]==1)
                                                             {
                                                                 [formData appendPartWithFileData:imageData name:imageKey fileName:@"file.jpeg" mimeType:@"image/jpeg"];
                                                             }
                                                             else if ([param[@"fileType"] intValue]==2)
                                                             {
                                                                 [formData appendPartWithFileData:imageData name:imageKey fileName:@"file.mp3" mimeType:@"audio/x-mpeg"];
                                                             }
                                                             else if ([param[@"fileType"] intValue]==3)
                                                             {
                                                                 [formData appendPartWithFileData:imageData name:imageKey fileName:@"file.mp4" mimeType:@"video/mp4"];
                                                             }
                                                             else
                                                             {
                                                                 [formData appendPartWithFileData:imageData name:imageKey fileName:@"file.jpeg" mimeType:@"image/jpeg"];
                                                             }
                                                         }
                                                         else
                                                         {
//                                                             [formData appendPartWithFileData:imageData name:imageKey fileName:@"file.jpeg" mimeType:@"image/jpeg"];
                                                             [formData appendPartWithFileData:imageData name:imageKey fileName:[NSString stringWithFormat:@"%@.jpeg",imageKey] mimeType:@"image/jpeg"];
                                                         }
                                                         
                                                     }
                                                 }
                                                 
                                             } success:^(AFHTTPRequestOperation *operation, id responseObject)
                                             {
                                                 LLog(@"\n_____requestUrl:%@\n",url);
                                                 if (result)
                                                 {
                                                     NSDictionary *dict = (NSDictionary *)responseObject;
                                                     if ([dict[Key_Code] integerValue]==-1)
                                                     {
                                                         [self pushToLoginVC];
                                                     }
                                                     
                                                     result([parser parseResponseDictionary:responseObject]);
                                                 }
                                                 
                                             } failure:^(AFHTTPRequestOperation *operation, NSError *error)
                                             {
                                                 LLog(@"\n_____requestUrl:%@\n",url);
                                                 if (failure)
                                                 {
                                                     failure(error);
                                                     LLog(@"error:%@",[error description]);
                                                 }
                                                 
                                             }];
        
        if (progress)
        {
            [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
             {
                 LLog(@"*************%lld,%lld,%lld",(long long)bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
                 if (progress)
                 {
                     progress((float)totalBytesWritten/totalBytesExpectedToWrite);
                 }
             }];
        }
        
    }
    else
    {
        [mgr POST:UrlJoint(Key_BaseUrl, url) parameters:[params buidlParam2Dictionary]
          success:^(AFHTTPRequestOperation *operation, id responseObj) {
              LLog(@"\n_____requestUrl:%@\n",url);
              if (result)
              {
                  NSDictionary *dict = (NSDictionary *)responseObj;
                  if ([dict[Key_Code] integerValue]==-1)
                  {
                      [self pushToLoginVC];
                  }
                  
                  result([parser parseResponseDictionary:responseObj]);
              }
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              LLog(@"\n_____requestUrl:%@\n",url);
              if (failure) {
                  failure(error);
                  LLog(@"error:%@",[error description]);
              }
          }];
    }

}

+ (void)pushToLoginVC
{
    [[NSNotificationCenter defaultCenter]postNotificationName:Notification_LoginDismiss object:nil];
}

@end
